import { ref } from 'vue'

// 主题配置
const themeConfig = ref({
  // 暗夜模式
  isDark: false,
  // 主题色
  primaryColor: '#409eff',
  // 语言
  language: 'zh'
})

// 预设主题色
export const presetColors = [
  '#409eff', // 默认蓝色
  '#67c23a', // 绿色
  '#e6a23c', // 橙色
  '#f56c6c', // 红色
  '#909399', // 灰色
  '#9c27b0', // 紫色
  '#ff9800', // 深橙色
  '#2196f3', // 浅蓝色
  '#4caf50', // 浅绿色
  '#ff5722'  // 深红色
]

// 从localStorage获取主题配置
export function getThemeConfig() {
  const saved = localStorage.getItem('theme-config')
  if (saved) {
    try {
      const config = JSON.parse(saved)
      themeConfig.value = { ...themeConfig.value, ...config }
    } catch (error) {
      console.error('解析主题配置失败:', error)
    }
  }
  return themeConfig.value
}

// 保存主题配置到localStorage
export function saveThemeConfig(config) {
  themeConfig.value = { ...themeConfig.value, ...config }
  localStorage.setItem('theme-config', JSON.stringify(themeConfig.value))
  applyTheme()
}

// 设置预设主题
export function setPresetTheme(themeName) {
  const theme = presetThemes.find(t => t.name === themeName)
  if (theme) {
    saveThemeConfig({
      primaryColor: theme.primaryColor,
      isDark: theme.isDark
    })
  }
}

// 获取当前主题名称
export function getCurrentThemeName() {
  const { primaryColor, isDark } = themeConfig.value
  const theme = presetThemes.find(t => 
    t.primaryColor === primaryColor && t.isDark === isDark
  )
  return theme ? theme.name : 'default'
}

// 切换暗夜模式
export function toggleDarkMode() {
  const newConfig = { isDark: !themeConfig.value.isDark }
  saveThemeConfig(newConfig)
}

// 设置主题色
export function setPrimaryColor(color) {
  saveThemeConfig({ primaryColor: color })
}

// 设置语言
export function setLanguage(lang) {
  saveThemeConfig({ language: lang })
  // 注意：在 Composition API 模式下，语言切换需要通过页面刷新来实现
  // 这是因为 i18n 实例在组件初始化时就确定了语言
}

// 应用主题
export function applyTheme() {
  const { isDark, primaryColor } = themeConfig.value
  
  // 应用暗夜模式
  if (isDark) {
    document.documentElement.classList.add('dark')
  } else {
    document.documentElement.classList.remove('dark')
  }
  
  // 生成主题色的搭配色
  const sidebarBgColor = generateSidebarColor(primaryColor, isDark)
  const sidebarHoverColor = generateHoverColor(primaryColor, isDark)
  const menuItemColor = generateMenuItemColor(primaryColor, isDark)
  
  // 应用主题色
  const style = document.createElement('style')
  style.id = 'theme-style'
  style.textContent = `
    :root {
      --el-color-primary: ${primaryColor} !important;
      --sidebar-bg-color: ${sidebarBgColor} !important;
      --sidebar-hover-color: ${sidebarHoverColor} !important;
      --menu-item-color: ${menuItemColor} !important;
    }
    
    .dark {
      --el-bg-color: #1a1a1a !important;
      --el-bg-color-page: #0a0a0a !important;
      --el-bg-color-overlay: #1d1e1f !important;
      --el-text-color-primary: #e5eaf3 !important;
      --el-text-color-regular: #cfd3dc !important;
      --el-text-color-secondary: #a3a6ad !important;
      --el-border-color: #4c4d4f !important;
      --el-border-color-light: #414243 !important;
      --el-fill-color-blank: #1a1a1a !important;
    }
    
    /* 侧边栏样式 - 恢复层次感 */
    .sidebar {
      background: var(--sidebar-bg-color) !important;
      transition: all 0.3s ease !important;
      position: relative !important;
    }
    
    .sidebar::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0.05) 50%, rgba(255,255,255,0) 100%);
      pointer-events: none;
      z-index: 1;
    }
    
    .sidebar-header {
      border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;
      background: transparent !important;
      position: relative;
      z-index: 2;
    }
    
    .dark .sidebar-header {
      border-bottom-color: rgba(255, 255, 255, 0.08) !important;
    }
    
    /* 菜单样式优化 - 恢复层次感 */
    .sidebar-menu {
      background-color: transparent !important;
      border: none !important;
      position: relative;
      z-index: 2;
    }
    
    .menu-item {
      color: rgba(255, 255, 255, 0.85) !important;
      background-color: transparent !important;
      border-radius: 8px !important;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
      position: relative !important;
      overflow: hidden !important;
    }
    
    .menu-item:hover {
      color: #fff !important;
      transform: translateX(4px) !important;
      background-color: transparent !important;
    }
    
    .menu-item.is-active {
      color: var(--el-color-primary) !important;
      background-color: transparent !important;
      font-weight: 600 !important;
    }
    
    .dark .menu-item {
      color: rgba(255, 255, 255, 0.85) !important;
    }
    
    .dark .menu-item:hover {
      color: #fff !important;
      background-color: transparent !important;
    }
    
    .dark .menu-item.is-active {
      color: var(--el-color-primary) !important;
      background-color: transparent !important;
      font-weight: 600 !important;
    }
    
    /* 子菜单样式 - 简化层次感 */
    .el-sub-menu__title {
      color: rgba(255, 255, 255, 0.85) !important;
      background-color: transparent !important;
      border-radius: 8px !important;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
      position: relative !important;
      overflow: hidden !important;
    }
    
    .el-sub-menu__title:hover {
      color: #fff !important;
      transform: translateX(4px) !important;
      background-color: transparent !important;
    }
    
    .dark .el-sub-menu__title {
      color: rgba(255, 255, 255, 0.85) !important;
    }
    
    .dark .el-sub-menu__title:hover {
      color: #fff !important;
      background-color: transparent !important;
    }
    
    /* 强制覆盖 Element Plus 的默认样式 */
    .el-menu-item:hover,
    .el-menu-item:focus,
    .el-sub-menu__title:hover,
    .el-sub-menu__title:focus {
      background-color: transparent !important;
    }
    
    .el-menu-item.is-active {
      background-color: transparent !important;
    }
    
    /* 确保子菜单项也不显示背景色 */
    .el-sub-menu .el-menu-item:hover,
    .el-sub-menu .el-menu-item:focus {
      background-color: transparent !important;
    }
    
    .el-sub-menu .el-menu-item.is-active {
      background-color: transparent !important;
    }
    
    /* 子菜单内容样式 - 简化 */
    .el-sub-menu .el-menu {
      background-color: transparent !important;
      border-radius: 4px !important;
      padding: 4px 0 !important;
    }
    
    .dark .el-sub-menu .el-menu {
      background-color: transparent !important;
    }
    
    /* 压缩状态样式 */
    .sidebar.collapsed {
      width: 64px !important;
    }
    
    .sidebar.collapsed .logo-text,
    .sidebar.collapsed .menu-text {
      display: none !important;
    }
    
    .sidebar.collapsed .sidebar-header {
      justify-content: center !important;
      padding: 0 12px !important;
    }
    
    .sidebar.collapsed .logo-icon {
      margin-right: 0 !important;
    }
    
    /* 其他组件暗夜模式适配 */
    .dark .el-card {
      background-color: var(--el-bg-color-overlay) !important;
      border-color: var(--el-border-color) !important;
      color: var(--el-text-color-primary) !important;
    }
    
    .dark .el-card__header {
      background-color: var(--el-bg-color) !important;
      border-bottom-color: var(--el-border-color) !important;
      color: var(--el-text-color-primary) !important;
    }
    
    .dark .el-table {
      background-color: var(--el-bg-color-overlay) !important;
      color: var(--el-text-color-primary) !important;
    }
    
    .dark .el-table th {
      background-color: var(--el-bg-color) !important;
      color: var(--el-text-color-primary) !important;
      border-bottom-color: var(--el-border-color) !important;
    }
    
    .dark .el-table td {
      background-color: var(--el-bg-color-overlay) !important;
      color: var(--el-text-color-primary) !important;
      border-bottom-color: var(--el-border-color) !important;
    }
    
    .dark .el-table--striped .el-table__body tr.el-table__row--striped td {
      background-color: var(--el-bg-color) !important;
    }
    
    .dark .el-table--enable-row-hover .el-table__body tr:hover > td {
      background-color: var(--el-fill-color-light) !important;
    }
    
    .dark .el-header {
      background-color: var(--el-bg-color-overlay) !important;
      border-bottom-color: var(--el-border-color) !important;
    }
    
    .dark .el-main {
      background-color: var(--el-bg-color-page) !important;
    }
    
    /* 按钮样式适配 */
    .dark .el-button {
      border-color: var(--el-border-color) !important;
    }
    
    .dark .el-button--default {
      background-color: var(--el-bg-color-overlay) !important;
      color: var(--el-text-color-primary) !important;
    }
    
    .dark .el-button--default:hover {
      background-color: var(--el-fill-color-light) !important;
      border-color: var(--el-color-primary) !important;
    }
    
    /* 输入框样式适配 */
    .dark .el-input__wrapper {
      background-color: var(--el-bg-color-overlay) !important;
      border-color: var(--el-border-color) !important;
    }
    
    .dark .el-input__inner {
      color: var(--el-text-color-primary) !important;
    }
    
    .dark .el-input__wrapper:hover {
      border-color: var(--el-color-primary) !important;
    }
    
    /* 下拉菜单样式适配 */
    .dark .el-dropdown-menu {
      background-color: var(--el-bg-color-overlay) !important;
      border-color: var(--el-border-color) !important;
    }
    
    .dark .el-dropdown-menu__item {
      color: var(--el-text-color-primary) !important;
    }
    
    .dark .el-dropdown-menu__item:hover {
      background-color: var(--el-fill-color-light) !important;
      color: var(--el-color-primary) !important;
    }
    
    /* 面包屑样式适配 */
    .dark .el-breadcrumb__item {
      color: var(--el-text-color-secondary) !important;
    }
    
    .dark .el-breadcrumb__inner {
      color: var(--el-text-color-secondary) !important;
    }
    
    .dark .el-breadcrumb__inner:hover {
      color: var(--el-color-primary) !important;
    }
    
    .dark .el-breadcrumb__item:last-child .el-breadcrumb__inner {
      color: var(--el-text-color-primary) !important;
    }
    
    /* 标签页样式适配 */
    .dark .el-tabs__header {
      border-bottom-color: var(--el-border-color) !important;
    }
    
    .dark .el-tabs__item {
      color: var(--el-text-color-regular) !important;
    }
    
    .dark .el-tabs__item:hover {
      color: var(--el-color-primary) !important;
    }
    
    .dark .el-tabs__item.is-active {
      color: var(--el-color-primary) !important;
    }
    
    /* 分页样式适配 */
    .dark .el-pagination {
      color: var(--el-text-color-primary) !important;
    }
    
    .dark .el-pagination .el-pager li {
      background-color: var(--el-bg-color-overlay) !important;
      color: var(--el-text-color-primary) !important;
    }
    
    .dark .el-pagination .el-pager li:hover {
      color: var(--el-color-primary) !important;
    }
    
    .dark .el-pagination .el-pager li.is-active {
      background-color: var(--el-color-primary) !important;
      color: #fff !important;
    }
  `
  
  // 移除旧的样式
  const oldStyle = document.getElementById('theme-style')
  if (oldStyle) {
    oldStyle.remove()
  }
  
  document.head.appendChild(style)
}

// 生成侧边栏背景色
function generateSidebarColor(primaryColor, isDark) {
  if (isDark) {
    // 暗夜模式：使用纯黑色背景，保持层次感
    return 'linear-gradient(180deg, #000000 0%, #1a1a1a 100%)'
  } else {
    // 浅色模式：使用主题色的深色版本，保持层次感
    const color = hexToRgb(primaryColor)
    if (!color) return 'linear-gradient(180deg, #001529 0%, #002140 100%)'
    
    // 生成深色背景，与主题色搭配但保持层次感
    const darkHue = color.h
    const darkSaturation = Math.min(80, color.s + 20)
    const darkLightness = Math.max(8, Math.min(15, color.l * 0.3))
    
    return `linear-gradient(180deg, hsl(${darkHue}, ${darkSaturation}%, ${darkLightness}%) 0%, hsl(${darkHue}, ${darkSaturation}%, ${darkLightness + 5}%) 100%)`
  }
}

// 生成悬停背景色
function generateHoverColor(primaryColor, isDark) {
  if (isDark) {
    // 暗夜模式：使用主题色的透明版本，保持层次感
    return `${primaryColor}25`
  } else {
    // 浅色模式：使用主题色的透明版本，保持层次感
    return `${primaryColor}20`
  }
}

// 生成菜单项背景色
function generateMenuItemColor(primaryColor, isDark) {
  if (isDark) {
    // 暗夜模式：使用深色背景
    return 'rgba(255, 255, 255, 0.05)'
  } else {
    // 浅色模式：使用主题色的深色透明版本
    return `${primaryColor}10`
  }
}

// 将十六进制颜色转换为 RGB
function hexToRgb(hex) {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
  if (!result) return null
  
  const r = parseInt(result[1], 16)
  const g = parseInt(result[2], 16)
  const b = parseInt(result[3], 16)
  
  // 转换为 HSL
  const hsl = rgbToHsl(r, g, b)
  
  return {
    r, g, b,
    h: hsl.h,
    s: hsl.s,
    l: hsl.l
  }
}

// RGB 转 HSL
function rgbToHsl(r, g, b) {
  r /= 255
  g /= 255
  b /= 255
  
  const max = Math.max(r, g, b)
  const min = Math.min(r, g, b)
  let h, s, l = (max + min) / 2
  
  if (max === min) {
    h = s = 0
  } else {
    const d = max - min
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
    
    switch (max) {
      case r: h = (g - b) / d + (g < b ? 6 : 0); break
      case g: h = (b - r) / d + 2; break
      case b: h = (r - g) / d + 4; break
    }
    h /= 6
  }
  
  return {
    h: Math.round(h * 360),
    s: Math.round(s * 100),
    l: Math.round(l * 100)
  }
}

// 初始化主题
export function initTheme() {
  getThemeConfig()
  applyTheme()
}

// 导出主题配置的响应式引用
export { themeConfig } 